<template>
  <div class="remote-panel-root">
    <div class="minbtn">
      <el-tag type="warning" class="minbtn-item" v-for="item in remotes" :key="item.uuid" @click="onMenu('show', item)" effect="dark">{{item.name}}</el-tag>
    </div>
    <Remote :onCloseForParent="onCloseForParent" :onMenu="onMenu" v-for="item in remotes" :data="item" :key="item.uuid"></Remote>
  </div>
</template>

<script>
import Remote from "./Remote.vue";

export default {
  name: "RemotePanel",
  components: {
    Remote,
  },
  data() {
    return {
      pingSetIntervalId: null,
      remotes: [],
    };
  },
  methods: {
    onCloseForParent(data) {
      for (let i = 0; i < this.remotes.length; i++) {
        const element = this.remotes[i];
        if (element.uuid === data.uuid) {
          this.remotes.splice(i, 1);
          break;
        }
      }
    },
    onMenu(action, data) {
      if (action === "min") {
        data.active = false;
        return;
      }

      if (action === "show") {
        data.active = true;
        return;
      }
    },
    addRemote(data) {
      for (const item of this.remotes) {
        item.active = false;
      }
      this.remotes.push(data);
    },
    pings() {
      if (this.remotes.length === 0) {
        return;
      }

      for (const item of this.remotes) {
        try {
          this.utils.http(
            "post",
            "/webapi/remotecpe/ping",
            {
              uuid: item.uuid,
            },
            () => { }
          );
        } catch (error) {
          console.log(error);
        }
      }
    },
  },
  mounted() {
    this.utils.on(this._uid, "event_remote_add", (data) => {
      this.addRemote(data);
    });

    this.pingSetIntervalId = setInterval(() => {
      this.pings();
    }, 5000);
  },
  destroyed() {
    this.utils.unon(this._uid, "event_remote_add");
  },
};
</script>

<style>
.remote-panel-root .minbtn {
  position: absolute;
  right: 10px;
  bottom: 10px;
}

.remote-panel-root .minbtn .minbtn-item {
  cursor: pointer;
  margin-left: 10px;
}
</style>